package model

import (
	"errors"
	"log"
	"raymond/global"
	"time"

	"github.com/jmoiron/sqlx"
)

const table_bnb_transaction_journal = "t_bnb_transaction_journal"

type BNBTransactionJournal struct {
	Id                int64     `db:"id"`
	BlockNumber       string    `db:"block_number"`
	TimeStamp         string    `db:"time_stamp"`
	Hash              string    `db:"hash"`
	Nonce             string    `db:"nonce"`
	BlockHash         string    `db:"block_hash"`
	FromAddr          string    `db:"from_addr"`
	ContractAddress   string    `db:"contract_address"`
	ToAddr            string    `db:"to_addr"`
	Value             string    `db:"value"`
	TokenName         string    `db:"token_name"`
	TokenSymbol       string    `db:"token_symbol"`
	TokenDecimal      string    `db:"token_decimal"`
	TransactionIndex  string    `db:"transaction_index"`
	Gas               string    `db:"gas"`
	GasPrice          string    `db:"gas_price"`
	GasUsed           string    `db:"gas_used"`
	CumulativeGasUsed string    `db:"cumulative_gas_used"`
	InputParams       string    `db:"input_params"`
	Confirmations     string    `db:"confirmations"`
	Remark            string    `db:"remark"`
	CreateTime        time.Time `db:"ct"`
	UpdateTime        time.Time `db:"ut"`
}

func (tx *BNBTransactionJournal) CreateBSNTxJournal() {
	now := time.Now().UTC()
	model := &BNBTransactionJournal{
		BlockNumber:       tx.BlockNumber,
		TimeStamp:         tx.TimeStamp,
		Hash:              tx.Hash,
		Nonce:             tx.Nonce,
		BlockHash:         tx.BlockHash,
		FromAddr:          tx.FromAddr,
		ContractAddress:   tx.ContractAddress,
		ToAddr:            tx.ToAddr,
		Value:             tx.Value,
		TokenName:         tx.TokenName,
		TokenSymbol:       tx.TokenSymbol,
		TokenDecimal:      tx.TokenDecimal,
		TransactionIndex:  tx.TransactionIndex,
		Gas:               tx.Gas,
		GasPrice:          tx.GasPrice,
		GasUsed:           tx.GasUsed,
		CumulativeGasUsed: tx.CumulativeGasUsed,
		InputParams:       tx.InputParams,
		Confirmations:     tx.Confirmations,
		Remark:            tx.Remark,
		CreateTime:        now,
		UpdateTime:        now,
	}
	result, err := global.DB().NamedExec("insert into "+table_bnb_transaction_journal+
		" (block_number, time_stamp, hash, nonce, block_hash, from_addr, contract_address, to_addr, value, "+
		" token_name, token_symbol, token_decimal, transaction_index, "+
		" gas, gas_price, gas_used, cumulative_gas_used, input_params, confirmations, "+
		" create_time, update_time)"+
		" values (:block_number, :time_stamp, :hash, :nonce, :block_hash, :from_addr, :contract_address, :to_addr, :value, "+
		" :token_name, :token_symbol, :token_decimal, :transaction_index, "+
		" :gas, :gas_price, :gas_used, :cumulative_gas_used, :input_params, :confirmations, "+
		" :ct,:ut)",
		&model)
	if err != nil {
		log.Println(err)
		return
	}
	tx.Id, _ = result.LastInsertId()
}

func AllBNBTxList() *[]BNBTransactionJournal {
	var txList []BNBTransactionJournal
	err := global.DB().Select(&txList, "select hash, from_addr, to_addr from "+table_bnb_transaction_journal)
	if err != nil {
		log.Println(err)
		return nil
	}
	return &txList
}

func BatchInsertBNBTxJournal(txJournals *[]BNBTransactionJournal) error {
	if txJournals == nil || len(*txJournals) <= 0 {
		return errors.New("空数组不能批量插入")
	}
	now := time.Now().UTC()
	insert := "insert into " + table_bnb_transaction_journal +
		" (block_number, time_stamp, hash, nonce, block_hash, " +
		" from_addr, contract_address, to_addr, value, " +
		" token_name, token_symbol, token_decimal, transaction_index, " +
		" gas, gas_price, gas_used, cumulative_gas_used, input_params, confirmations, " +
		" create_time, update_time) values "

	vals := []interface{}{}
	for _, tj := range *txJournals {
		insert += "(?,?,?,?,?, ?,?,?,?, ?,?,?,?, ?,?,?,?,?,?, ?,?),"
		vals = append(vals, tj.BlockNumber, tj.TimeStamp, tj.Hash, tj.Nonce, tj.BlockHash,
			tj.FromAddr, tj.ContractAddress, tj.ToAddr, tj.Value,
			tj.TokenName, tj.TokenSymbol, tj.TokenDecimal, tj.TransactionIndex,
			tj.Gas, tj.GasPrice, tj.GasUsed, tj.CumulativeGasUsed, tj.InputParams, tj.Confirmations,
			now, now)
	}
	// 去掉最后的逗号
	insert = insert[0 : len(insert)-1]

	insert, args, err := sqlx.In(insert, vals...)
	if err != nil {
		return err
	}

	insert = global.DB().Rebind(insert)

	_, err = global.DB().Exec(insert, args...)
	if err != nil {
		return err
	}
	return nil
}
